package com.ncloud.crm.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ncloud.param.service.SequenceService;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.BsNodeAttr;
import com.ncloud.crm.entity.order.WorkNodeAttr;
import com.ncloud.crm.mapper.WorkNodeAttrMapper;
import com.ncloud.crm.service.BsNodeAttrService;
import com.ncloud.crm.service.WorkNodeAttrService;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.crm.utils.ItemInfoUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;
import com.ncloud.param.service.TagService;

@Service
public class WorkNodeAttrServiceImpl implements WorkNodeAttrService {
	
	private static final Logger logger = LogManager.getLogger(WorkNodeAttrServiceImpl.class);
	
	@Autowired
	private WorkNodeAttrMapper workNodeAttrMapper;
	@Autowired
	private BsNodeAttrService bsNodeAttrService;
	@Reference
	private SequenceService sequenceService;
	@Reference
	private TagService tagService;

	public JSONArray getId(JSONObject json) {
		if(json==null || !json.containsKey("workId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		List<WorkNodeAttr> orderAttrs = workNodeAttrMapper.getWorkNodeAttrByWorkId(json.getLong("workId"));
		return JSON.parseArray(JSON.toJSONString(orderAttrs));
	}

	@Override
	public JSONObject getPk(JSONObject json) {
		return null;
	}

	@Override
	public JSONObject validate(JSONObject json,JSONObject result) {
		JSONObject jsonObject = new JSONObject();
		return jsonObject;
	}

	@Override
	public void nodeItemInfos(JSONObject node,JSONObject result,JSONArray array,String tiemKey){
		//处理节点属性

		String currentDataTime = DateUtils.getDateTime();
		/*提取要处理的属性信息*/
		//JSONObject nodeItems = new JSONObject();
		List<String> keys = getAttrKeys(tiemKey);
		/*声明查询条件*/
		BsNodeAttr paramAttr = new BsNodeAttr();
		paramAttr.setAttrType(Constant.ATTR_TYPE_NODE);
		paramAttr.setNodeId(result.getLong( TableIdDefineUtils.NODE_ID));
		Date date = new Date();
		paramAttr.setBeginDate(date);
		paramAttr.setEndDate(date);
		for (Map.Entry<String, Object> entry : node.entrySet()) {
			WorkNodeAttr workNodeAttrNew = new WorkNodeAttr();
			String key = entry.getKey();
			/*处理配置的属性*/
			if(keys.contains(key)){
				/*对金额的属性进行处理*/
				String value = ItemInfoUtils.isMoney(key)?String.valueOf(ItemInfoUtils.getMultiMoney(entry.getValue(),100)):String.valueOf(entry.getValue());
				//nodeItems.put(key,entry.getValue());
				paramAttr.setAttrCode(key);
				BsNodeAttr bsNodeAttrOld = bsNodeAttrService.getValidNodeAttr(paramAttr);
				if(bsNodeAttrOld != null){
					WorkNodeAttr workNodeAttrOld = JSON.parseObject(JSON.toJSONString(bsNodeAttrOld),WorkNodeAttr.class);
					workNodeAttrOld.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
					workNodeAttrOld.setEndDate(DateUtils.parseDate(currentDataTime));
					workNodeAttrOld.setModifyTag(Constant.DEL);
											/*保存原来信息*/
					array.add(JSON.parseObject(JSON.toJSONString(workNodeAttrOld)));
					/*增加一条新信息*/
					workNodeAttrNew.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
					workNodeAttrNew.setNodeId(result.getLong( TableIdDefineUtils.NODE_ID));
					workNodeAttrNew.setModifyTag(Constant.ADD);
					workNodeAttrNew.setAttrType(Constant.ATTR_TYPE_NODE);
					workNodeAttrNew.setBeginDate(DateUtils.parseDate(currentDataTime));
					workNodeAttrNew.setEndDate(DateUtils.parseDate(Constant.END_DATE));
					workNodeAttrNew.setAttrCode(key);
					workNodeAttrNew.setAttrValue(value);
				}else{
					workNodeAttrNew.setWorkId(result.getLong(TableIdDefineUtils.WORK_ID));
					workNodeAttrNew.setNodeId(result.getLong( TableIdDefineUtils.NODE_ID));
					workNodeAttrNew.setModifyTag(Constant.ADD);
					workNodeAttrNew.setAttrType(Constant.ATTR_TYPE_NODE);
					workNodeAttrNew.setBeginDate(DateUtils.parseDate(currentDataTime));
					workNodeAttrNew.setEndDate(DateUtils.parseDate(Constant.END_DATE));
					workNodeAttrNew.setAttrCode(key);
					workNodeAttrNew.setAttrValue(value);
				}
				array.add(JSON.parseObject(JSON.toJSONString(workNodeAttrNew)));
			}
		}
	}
	@Override
	public JSONObject insert(JSONObject json) {

		WorkNodeAttr orderAttr = JSON.parseObject(json.toJSONString(),WorkNodeAttr.class);
		try {
			validation(orderAttr);
			workNodeAttrMapper.insertWorkNodeAttr(orderAttr);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}
	private void validation(WorkNodeAttr workAttr){
		if(workAttr.getAttrId() == null){
			Long id = sequenceService.getSequence("seq_item_id");
			workAttr.setAttrId(id);
		}
	}

	private List<String> getAttrKeys(String tagCode){
		List<String> list = new ArrayList<String>();
		JSONObject tagParam = new JSONObject();
		tagParam.put("tagCode",tagCode);
		JSONArray tagArray = tagService.getTagInfo(tagParam);
		String tagInfo = tagArray.getJSONObject(0).getString("tagInfo");
		if(tagInfo !=null){
			String[] tagKeys = tagInfo.split(",");
			list = Arrays.asList(tagKeys);
		}
		return list;
	}
	@Override
	public List<WorkNodeAttr> getNodeAttrsByWorkId(Long workId) {
		return workNodeAttrMapper.getWorkNodeAttrByWorkId(workId);
	}

/*	private boolean isMoney(String code){
		boolean flag = false;
		List<String> keys = new ArrayList<String>();
		keys.add("payMoney");
		keys.add("minFee");
		keys.add("maxFee");
		if(keys.contains(code)){
			flag = true;
		}

		return flag;
	}*/
}
